package io.oschina.binv.kapp.framework.utils

import android.content.Context
import android.media.MediaScannerConnection
import android.net.Uri

/**
 * Desction:媒体扫描工具类
 * 调用MediaScanner.scanFile("/sdcard/1.jpeg");
 */
class MediaScanner(context: Context) {
    val Log= Logger(this::class.java.canonicalName)
    private val mediaScanConn: MediaScannerConnection by lazy {
        MediaScannerConnection(context, MusicSannerClient())
    }
    private var fileType: String = ""
    private var filePaths: Array<String> = emptyArray()
    private var onScanCompleted: (images: Array<String>)->Unit = {}
    /**
     * 扫描文件标签信息
     *
     * @param filePath 文件路径
     * @param fileType 文件类型
     */

    fun scanFile(filePath: String, fileType: String="image/jpeg", onScanCompleted: (images: Array<String>)->Unit={}) {
        this.filePaths = arrayOf(filePath)
        this.fileType = fileType
        this.onScanCompleted = onScanCompleted
        //连接之后调用MusicSannerClient的onMediaScannerConnected()方法
        mediaScanConn.connect()
    }

    /**
     * @param filePaths 文件路径
     * @param fileType  文件类型
     */
    fun scanFile(filePaths: Array<String>, fileType: String, onScanCompleted: (images: Array<String>)->Unit={}) {
        this.filePaths = filePaths
        this.fileType = fileType
        this.onScanCompleted = onScanCompleted
        mediaScanConn.connect()
    }

    fun unScanFile() {
        mediaScanConn.disconnect()
    }

    private inner class MusicSannerClient : MediaScannerConnection.MediaScannerConnectionClient {
        override fun onMediaScannerConnected() {
            Log.i("onMediaScannerConnected")
            filePaths.forEach {
                file->
                mediaScanConn.scanFile(file, fileType)
            }
        }

        override fun onScanCompleted(path: String, uri: Uri) {
            Log.i("onScanCompleted")
            mediaScanConn.disconnect()
            onScanCompleted(filePaths.clone())
        }
    }
}